package net.huashitong.supervision.appController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.DeptService;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import com.sirdc.modules.utils.date.DateUtils;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.*;
import net.huashitong.supervision.task.service.*;
import net.huashitong.supervision.task.service.SpecialService.TaskSpecialService;
import net.huashitong.util.UtilsTools;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/11/6
 * Time: 9:59
 * To change this template use File | Settings | File Templates.
 * Description:
 * 单位内部督查
 */
@Controller
@RequestMapping(value = "/appTaskUnit")
public class AppTaskUnitContorller extends JsonBaseController {
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private TaskCategoryService categoryService;
    @Autowired
    private SMSUtilService smsUtilService;
    @Autowired
    private TaskMainService taskMainService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TaskUserService taskUserService;
    @Autowired
    private MajorBackService majorBackService;
    @Autowired
    private TaskUnitService taskUnitService;
    @Autowired
    private TaskBackNewService taskBackNewService;
    @Autowired
    private HastenMessageService hastenMessageService;
    @Autowired
    private TaskLogNewService taskLogNewService;


    @Override
    protected String getView(String s) {
        return null;
    }

    /**
     * 内部立项批转人员列表
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/endorseList2", method = RequestMethod.POST)
    public Message endorseList2(@RequestBody SysUser user) {
        String userId = "";
        if (StringUtils.isBlank(user.getSysId())) {
            userId = SysUserUtils.getUserId();
        } else {
            userId = user.getSysId();
        }
        user.setSysId(userId);
        List<SysUser> userList = sysLoginService.queryLowerList(user);
        return coverMessage("200", "success", userList);
    }
    /*=============================单位内部功能===============================*/

    /**
     * 单位内部立项
     *
     * @param json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createTask", method = RequestMethod.POST)
    public Message createTask(@RequestBody AppMainFilter json) {
        TaskMainFilter filter = JSON.parseObject(json.getJson(), TaskMainFilter.class);
        if (StringUtils.isBlank(filter.getMainName())) {
            return coverMessage(UtilsTools.ERROR, "请填写任务名");
        }
        //如果不是周期性任务，需填写任务时限
        if ("1".equals(filter.getTimeType())) {
            if (StringUtils.isBlank(filter.getTimeLimit())) {
                return coverMessage(UtilsTools.ERROR, "请填写任务时限");
            }
        } else if ("2".equals(filter.getTimeType())) {
            if ("0".equals(filter.getPeriod())) {
                if (StringUtils.isBlank(filter.getDay())) {
                    return coverMessage(UtilsTools.ERROR, "请填写任务时限");
                }
            } else if ("1".equals(filter.getPeriod())) {
                if (StringUtils.isBlank(filter.getWeek())) {
                    return coverMessage(UtilsTools.ERROR, "请填写任务时限");
                }
            } else if ("2".equals(filter.getPeriod())) {
                if (StringUtils.isBlank(filter.getMonth())) {
                    return coverMessage(UtilsTools.ERROR, "请填写任务时限");
                }
            } else {
                if (StringUtils.isBlank(filter.getQuarter())) {
                    return coverMessage(UtilsTools.ERROR, "请填写任务时限");
                }
            }
        } else {
            if (StringUtils.isBlank(filter.getTimeLimits())) {
                return coverMessage(UtilsTools.ERROR, "请填写任务时限");
            }
        }

        if (StringUtils.isBlank(filter.getTasksubfilterlist())) {
            return coverMessage("500", "立项失败");
        } else {
            JSONArray array = JSON.parseArray(filter.getTasksubfilterlist());
            filter.setTaskSubFilterList(array.toJavaList(TaskSubFilter.class));
        }
        String s = null;
        try {
            s = taskUnitService.createTask(filter);
        } catch (ParseException e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
        if ("200".equals(s)) {
            return coverMessage("200", "保存成功");
        } else {
            return coverMessage("500", s);
        }
    }

    /**
     * 内部待办(我创建的)
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dbNeibu", method = RequestMethod.POST)
    public Message dbNeibu(@RequestBody TaskUnitFilter filter) {
        try {
            String userId = filter.getUserId();
            SysUserDataBean dataBean = sysUserService.getUserDataBeanById(userId);
            if (StringUtils.isNotBlank(filter.getSearch())) {
                filter.setTaskMainName(filter.getSearch());
                filter.setTaskSubName(filter.getSearch());
            }
            filter.setUserId(userId);
            filter.setDeptId(dataBean.getDeptId());
            filter.setCategoryId("20191022100000000002");
            List<TaskUnit> unDoneUnit = taskUnitService.getUnDoneUnit(filter);
            if (ObjectUtils.isNotBlank(unDoneUnit)) {
                return coverMessage("200", "我创建的内部任务", unDoneUnit);
            } else {
                return coverMessage("500", "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 内部在办(我创建的)
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/zbNeibu", method = RequestMethod.POST)
    public Message zbNeibu(@RequestBody TaskUnitFilter filter) {
        try {
            String userId = filter.getUserId();
            SysUserDataBean dataBean = sysUserService.getUserDataBeanById(userId);
            if (StringUtils.isNotBlank(filter.getSearch())) {
                filter.setTaskMainName(filter.getSearch());
                filter.setTaskSubName(filter.getSearch());
            }
            filter.setUserId(userId);
            filter.setDeptId(dataBean.getDeptId());
            filter.setCategoryId("20191022100000000002");
            List<TaskUnit> nowUnit = taskUnitService.getNowUnit(filter);
            if (ObjectUtils.isNotBlank(nowUnit)) {
                return coverMessage("200", "我创建的内部任务", nowUnit);
            } else {
                return coverMessage("500", "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 内部已完成办(我创建的)
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/ywcNeibu", method = RequestMethod.POST)
    public Message ywcNeibu(@RequestBody TaskUnitFilter filter) {
        try {
            String userId = filter.getUserId();
            SysUserDataBean dataBean = sysUserService.getUserDataBeanById(userId);
            if (StringUtils.isNotBlank(filter.getSearch())) {
                filter.setTaskMainName(filter.getSearch());
                filter.setTaskSubName(filter.getSearch());
            }
            filter.setUserId(userId);
            filter.setDeptId(dataBean.getDeptId());
            filter.setType("4");
            filter.setCategoryId("20191022100000000002");
            List<TaskUnit> doneUnit = taskUnitService.queryFilter(filter);
            if (ObjectUtils.isNotBlank(doneUnit)) {
                return coverMessage("200", "我创建的内部任务", doneUnit);
            } else {
                return coverMessage("500", "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 内部全部(我创建的)
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/allNeibu", method = RequestMethod.POST)
    public Message allNeibu(@RequestBody TaskUnitFilter filter) {
        try {
            String userId = filter.getUserId();
            SysUserDataBean dataBean = sysUserService.getUserDataBeanById(userId);
            if (StringUtils.isNotBlank(filter.getSearch())) {
                filter.setTaskMainName(filter.getSearch());
                filter.setTaskSubName(filter.getSearch());
            }
            filter.setUserId(userId);
            filter.setDeptId(dataBean.getDeptId());
            filter.setCategoryId("20191022100000000002");
            List<TaskUnit> allUnit = taskUnitService.queryFilter(filter);
            if (ObjectUtils.isNotBlank(allUnit)) {
                return coverMessage("200", "我创建的内部任务", allUnit);
            } else {
                return coverMessage("500", "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 内部y逾期(我创建的)
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/yqNeibu", method = RequestMethod.POST)
    public Message yqNeibu(@RequestBody TaskUnitFilter filter) {
        try {
            List<TaskUnit> yqList = new ArrayList<>();
            String userId = filter.getUserId();
            SysUserDataBean dataBean = sysUserService.getUserDataBeanById(userId);
            if (StringUtils.isNotBlank(filter.getSearch())) {
                filter.setTaskMainName(filter.getSearch());
                filter.setTaskSubName(filter.getSearch());
            }
            filter.setUserId(userId);
            filter.setDeptId(dataBean.getDeptId());
            filter.setCategoryId("20191022100000000002");
            List<TaskUnit> nowUnit = taskUnitService.getNowUnit(filter);
            for (TaskUnit taskUnit : nowUnit) {
                if (taskUnit.getOverdueDay() != null) {
                    yqList.add(taskUnit);
                }
            }
            if (ObjectUtils.isNotBlank(yqList)) {
                return coverMessage("200", "我创建的内部任务", yqList);
            } else {
                return coverMessage("500", "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }

    }

    /**
     * 办理单位内部任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/handleTask", method = RequestMethod.POST)
    public Message handleTask(@RequestBody TaskUnitFilter filter) {
        try {
            TaskUnit taskUnit = taskUnitService.getById(filter.getSysId());
            taskUnit.setType("4");
            List<TaskUser> taskUsers = taskUserService.getByTaskUnitId(taskUnit.getSysId());
            for (TaskUser taskUser : taskUsers) {
                //设置人员任务为完成
                taskUser.setStatus("4");
                taskUserService.update(taskUser);
            }
            taskUnitService.update(taskUnit);
            return coverMessage("200", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /*============================================单位内部立项功能=====================================*/

    /**
     * 单位任务 的待办
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dbTaskUnit", method = RequestMethod.POST)
    public Message dbTaskUnit(@RequestBody TaskUnitFilter filter) {
        String userId = filter.getUserId();
        if (StringUtils.isNotBlank(filter.getSearch())) {
            filter.setTaskSubName(filter.getSearch());
        }
        SysLogin login = sysLoginService.getById(userId);
        List<TaskUnit> taskUnitList = new ArrayList<>();
        String roleId = login.getRoleId();
        //如果是单位主要领导管理员，查看单位所有的 任务
        if ("02".equals(roleId)) {
            String deptId = login.getDeptId();
            filter.setDeptId(deptId);
            filter.setUserId(null);
            filter.setStatus("2");
            filter.setState("0");
            taskUnitList = taskUnitService.getUnDoneUnit(filter);
            //查询当前
        } else {
            //只查看自己的任务
            filter.setUserId(userId);
            taskUnitList = taskUnitService.getUnDoneUser(filter);
        }
        if (ObjectUtils.isNotBlank(taskUnitList)) {
            return coverMessage("200", "success", taskUnitList);
        } else {
            return coverMessage("500", "无任务");
        }
    }

    /**
     * 单位负责的待办单位重大事项
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dbZDMain", method = RequestMethod.POST)
    public Message dbZDMain(@RequestBody TaskMainFilter filter) {
        String overdueDept = filter.getOverdueDept();
        filter.setOverdueDept(overdueDept);
        //单位督办任务
        List<TaskMain> overdueDeptMain = taskMainService.queryDBOverdueDept(filter);
        if (ObjectUtils.isNotBlank(overdueDeptMain)) {
            return coverMessage("200", "success", overdueDeptMain);
        } else {
            return coverMessage("500");
        }
    }

    /**
     * 单位在办的任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/zbTaskUnit", method = RequestMethod.POST)
    public Message zbTaskUnit(@RequestBody TaskUnitFilter filter) {
        String userId = filter.getUserId();
        if (StringUtils.isNotBlank(filter.getSearch())) {
            filter.setTaskSubName(filter.getSearch());
        }
        SysLogin login = sysLoginService.getById(userId);
        List<TaskUnit> taskUnitList = new ArrayList<>();
        String roleId = login.getRoleId();
        //如果是单位主要领导管理员，查看单位所有的 任务
        if ("02".equals(roleId)) {
            String deptId = login.getDeptId();
            filter.setDeptId(deptId);
            filter.setUserId(null);
            filter.setType("4");
            taskUnitList = taskUnitService.getNowUnit(filter);
        } else {
            //只查看自己的任务
            filter.setUserId(userId);
            taskUnitList = taskUnitService.getNowUser(filter);
        }
        if (ObjectUtils.isNotBlank(taskUnitList)) {
            return coverMessage("200", "success", taskUnitList);
        } else {
            return coverMessage("500", "无任务");
        }
    }


    /**
     * 单位负责的在办单位重大事项
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/zbZDMain", method = RequestMethod.POST)
    public Message zbZDMain(@RequestBody TaskMainFilter filter) {
        String overdueDept = filter.getOverdueDept();
        filter.setOverdueDept(overdueDept);
        //单位督办任务
        List<TaskMain> overdueDeptMain = taskMainService.queryZBOverdueDept(filter);
        if (ObjectUtils.isNotBlank(overdueDeptMain)) {
            return coverMessage("200", "success", overdueDeptMain);
        } else {
            return coverMessage("500");
        }
    }

    /**
     * 单位完成的任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wcTaskUnit", method = RequestMethod.POST)
    public Message wcTaskUnit(@RequestBody TaskUnitFilter filter) {
        String userId = filter.getUserId();
        if (StringUtils.isNotBlank(filter.getSearch())) {
            filter.setTaskSubName(filter.getSearch());
        }
        SysLogin login = sysLoginService.getById(userId);
        List<TaskUnit> taskUnitList = new ArrayList<>();
        String roleId = login.getRoleId();
        //如果是单位主要领导管理员，查看单位所有的 任务
        if ("02".equals(roleId)) {
            String deptId = login.getDeptId();
            filter.setDeptId(deptId);
            filter.setType("4");
            filter.setUserId(null);
            taskUnitList = taskUnitService.queryFilter(filter);
        } else {
            //只查看自己的任务
            filter.setUserId(userId);
            taskUnitList = taskUnitService.getDoneUser(filter);
        }
        if (ObjectUtils.isNotBlank(taskUnitList)) {
            return coverMessage("200", "success", taskUnitList);
        } else {
            return coverMessage("500", "无任务");
        }
    }

    /**
     * 单位负责的已完成单位重大事项
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wcZDMain", method = RequestMethod.POST)
    public Message wcZDMain(@RequestBody TaskMainFilter filter) {
        String overdueDept = filter.getOverdueDept();
        filter.setOverdueDept(overdueDept);
        //单位督办任务
        List<TaskMain> overdueDeptMain = taskMainService.queryWCOverdueDept(filter);
        if (ObjectUtils.isNotBlank(overdueDeptMain)) {
            return coverMessage("200", "success", overdueDeptMain);
        } else {
            return coverMessage("500");
        }
    }

    /**
     * 单位qunabu的任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/allTaskUnit", method = RequestMethod.POST)
    public Message allTaskUnit(@RequestBody TaskUnitFilter filter) {
        String userId = filter.getUserId();
        if (StringUtils.isNotBlank(filter.getSearch())) {
            filter.setTaskSubName(filter.getSearch());
        }
        SysLogin login = sysLoginService.getById(userId);
        List<TaskUnit> taskUnitList = new ArrayList<>();
        String roleId = login.getRoleId();
        //如果是单位主要领导管理员，查看单位所有的 任务
        if ("02".equals(roleId)) {
            String deptId = login.getDeptId();
            filter.setDeptId(deptId);
            filter.setUserId(null);
            taskUnitList = taskUnitService.queryFilter(filter);
        } else {
            //只查看自己的任务
            filter.setUserId(userId);
            taskUnitList = taskUnitService.getAllUser(filter);
        }
        if (ObjectUtils.isNotBlank(taskUnitList)) {
            return coverMessage("200", "success", taskUnitList);
        } else {
            return coverMessage("500", "无任务");
        }
    }

    /**
     * 单位负责的quanbu单位重大事项
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/allZDMain", method = RequestMethod.POST)
    public Message allZDMain(@RequestBody TaskMainFilter filter) {
        String overdueDept = filter.getOverdueDept();
        filter.setOverdueDept(overdueDept);
        //单位督办任务
        List<TaskMain> overdueDeptMain = taskMainService.queryOverdueDept(filter);
        for (TaskMain taskMain : overdueDeptMain) {
            taskMain.setCategoryId(categoryService.getById(taskMain.getCategoryId()).getCategory());
        }
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtils.isNotBlank(overdueDeptMain)) {
            map.put("list", overdueDeptMain);
            return coverMessage("200", "success", map);
        } else {
            return coverMessage("500", "无任务");
        }
    }

    @Autowired
    private SpecialTaskService specialTaskService;
    /**
     * 修改后的单位重大事项列表
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/specialTaskList",method = RequestMethod.POST)
    public Message specialTaskList(@RequestBody  SpecialTaskFilter filter){
        System.out.println(" ======== 重大事项 =========");
        class SpecialResult {
            private TaskMain taskMain;
            private SpecialTask specialTask;
            public TaskMain getTaskMain() {
                return taskMain;
            }

            public void setTaskMain(TaskMain taskMain) {
                this.taskMain = taskMain;
            }

            public SpecialTask getSpecialTask() {
                return specialTask;
            }
            public void setSpecialTask(SpecialTask specialTask) {
                this.specialTask = specialTask;
            }
        }
        List<SpecialResult> specialResults = new ArrayList<>();
        //当前登录用户
        SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(filter.getUserId());
        if (ObjectUtils.isBlank(userDataBean)){
            return coverMessage("500","无用户");
        }

        //单位督办任务 根据用户锁在单位取出他的所有子任务
        TaskMainFilter taskMainFilter = new TaskMainFilter();
        taskMainFilter.setOverdueDept(userDataBean.getDeptId());
        List<TaskMain> overdueDeptMain = taskMainService.queryOverdueDept(taskMainFilter);
        if(ObjectUtils.isBlank(overdueDeptMain)){
            return coverMessage("500","无任务");
        }

        HashMap<String, Object> map = new HashMap<>();
        filter.setOverdueDeptId(userDataBean.getDeptId());
        for (TaskMain taskMain : overdueDeptMain) {
            filter.setTaskMainId(taskMain.getSysId());
            taskMain.setCategoryId(categoryService.getById(taskMain.getCategoryId()).getCategory());//设置任务类型的名称；
            //查询当前主任务的轮次
            List<SpecialTask> list= specialTaskService.queryFilter(filter);
            if (ObjectUtils.isBlank(list)){
                continue;
            }
            SpecialResult specialResult = new SpecialResult();
            specialResult.setTaskMain(taskMain);

            if (list.size()>1){
               //有多轮任务,查询多轮任务状态
                for (SpecialTask specialTask : list) {
                    if ("4".equals(specialTask.getType())&&(Integer.parseInt(specialTask.getTimeRound())<list.size())){
                        //已完成,不显示
                    }else{
                        //未完成,显示  将特殊任务记录加入结果list
                        specialResult = new SpecialResult();
                        specialResult.setTaskMain(taskMain);
                        specialResult.setSpecialTask(specialTask);
                        specialResults.add(specialResult);
                    }
                }
            }else{
                //只有一轮,将该轮任务直接加入结果list;
                specialResult.setSpecialTask( list.get(0));
                specialResults.add(specialResult);
            }
        }
        if (ObjectUtils.isNotBlank(specialResults)){
            return coverMessage("200","单位重大事项列表",specialResults);
        }else{
            return coverMessage("500","无重大事项");
        }
    }

    /**
     * 当前单位该重大事项的汇总反馈历史记录
     *
     * @param majorBack
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/majorList", method = RequestMethod.POST)
    public Message majorList(@RequestBody MajorBack majorBack) {
        try {
            List<MajorBack> majorBacks = majorBackService.getByTaskMainId(majorBack.getTaskMainId());
            if (ObjectUtils.isNotBlank(majorBacks)) {
                return coverMessage("200", "汇总列表", majorBacks);
            } else {
                return coverMessage("500", "无记录");
            }
        } catch (Exception e) {
            e.printStackTrace();
             return coverMessage("500", e .getMessage());
        }
    }

    /**
     * 当前重点任务的承办单位
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/specialDeptList",method = RequestMethod.POST)
    public Message specialDeptList(@RequestBody SpecialTaskFilter filter){
        String taskMainId = filter.getTaskMainId();
        List<TaskUnit> units=taskUnitService.getByMainIdOneRound(taskMainId);
        if(ObjectUtils.isNotBlank(units)){
            return coverMessage("200","承办单位列表",units);
        }else{
            return coverMessage("500","错误");
        }
        
    }

    /**
     * 单位重大任务 督查单位汇总主任务结果反馈至督查组
     *
     * @param filter
     * @return
     */
    @Autowired
    private TaskSpecialService tpservice;
    @ResponseBody
    @RequestMapping(value = "/saveMainResult", method = RequestMethod.POST)
    public Message saveMainResult(@RequestBody TaskMainFilter filter) {

        int i = tpservice.dubanFeedBack(filter);
        if(i>0){
            return coverMessage("500","操作失败");
        }

        return coverMessage("200", "反馈成功");
    }

    /**
     * 单位的逾期任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/yqTaskUnit", method = RequestMethod.POST)
    public Message yqTaskUnit(@RequestBody TaskUnitFilter filter) {
        List<TaskUnit> yqList = new ArrayList<>();
        if (StringUtils.isNotBlank(filter.getSearch())) {
            filter.setTaskSubName(filter.getSearch());
        }
        String userId = filter.getUserId();
        SysLogin login = sysLoginService.getById(userId);
        List<TaskUnit> taskUnitList = new ArrayList<>();
        String roleId = login.getRoleId();
        //如果是单位主要领导管理员，查看单位所有的 任务
        if ("02".equals(roleId)) {
            String deptId = login.getDeptId();
            filter.setUserId(null);
            filter.setDeptId(deptId);
            filter.setType("4");
            taskUnitList = taskUnitService.getNowUnit(filter);
            for (TaskUnit taskUnit : taskUnitList) {
                if (taskUnit.getOverdueDay() != null) {
                    yqList.add(taskUnit);
                }
            }
        } else {
            //只查看自己的任务
            filter.setUserId(userId);
            taskUnitList = taskUnitService.getNowUser(filter);
            for (TaskUnit taskUnit : taskUnitList) {
                if (taskUnit.getOverdueDay() != null) {
                    yqList.add(taskUnit);
                }
            }
        }
        if (ObjectUtils.isNotBlank(yqList)) {
            return coverMessage("200", "success", yqList);
        } else {
            return coverMessage("500", "无任务");
        }
    }


    /**
     * 单位的cuiban任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/thcbTaskUnit", method = RequestMethod.POST)
    public Message thcbTaskUnit(@RequestBody TaskUnitFilter filter) {
        List<TaskUnit> thcbList = new ArrayList<>();
        String userId = filter.getUserId();
        if (StringUtils.isNotBlank(filter.getSearch())) {
            filter.setTaskSubName(filter.getSearch());
        }
        SysLogin login = sysLoginService.getById(userId);
        List<TaskUnit> taskUnitList = new ArrayList<>();
        String roleId = login.getRoleId();
        //如果是单位主要领导管理员，查看单位所有的 任务
        if ("02".equals(roleId)) {
            String deptId = login.getDeptId();
            filter.setUserId(null);
            filter.setDeptId(deptId);
            filter.setType("4");
            taskUnitList = taskUnitService.getNowUnit(filter);
            for (TaskUnit taskUnit : taskUnitList) {
                if ("3".equals(taskUnit.getType())) {
                    thcbList.add(taskUnit);
                }
            }
        } else {
            //只查看自己的任务
            filter.setUserId(userId);
            taskUnitList = taskUnitService.getNowUser(filter);
            for (TaskUnit taskUnit : taskUnitList) {
                if ("3".equals(taskUnit.getType())) {
                    thcbList.add(taskUnit);
                }
            }
        }
        if (ObjectUtils.isNotBlank(thcbList)) {
            return coverMessage("200", "success", thcbList);
        } else {
            return coverMessage("500", "无任务");
        }
    }

    /**
     * 催办信息列表
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "cbMessage", method = RequestMethod.POST)
    public Message cbMessage(@RequestBody SysUserDataBean dataBean) {
        String userId = dataBean.getUserId();
        //未读催办
        HastenMessageFilter hastenMessageFilter = new HastenMessageFilter();
        hastenMessageFilter.setUserId(userId);
//        hastenMessageFilter.setStatus("0");
        List<HastenMessage> hastenMessageList = hastenMessageService.queryFilter(hastenMessageFilter);
        if (ObjectUtils.isNotBlank(hastenMessageList)) {
            return coverMessage("200", "success", hastenMessageList);
        } else {
            return coverMessage("500", "无催办信息");
        }
    }

    /**
     * 更新催办信息状态
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateCb", method = RequestMethod.POST)
    public Message updateCb(@RequestBody HastenMessageFilter filter) {
        String sysId = filter.getSysId();
        HastenMessage message = hastenMessageService.getById(sysId);
        if (ObjectUtils.isBlank(message)) {
            return coverMessage("500", "error");
        }
        message.setStatus("1");
        hastenMessageService.update(message);
        return coverMessage("200", "success");
    }


    /**
     * 签收批转列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/signList", method = RequestMethod.POST)
    public Message signList(@RequestBody TaskUnitFilter filter) {
        String userId = filter.getUserId();
        if (StringUtils.isNotBlank(filter.getSearch())) {
            filter.setTaskSubName(filter.getSearch());
        }
        SysLogin login = sysLoginService.getById(userId);
        List<TaskUnit> taskUnitList = new ArrayList<>();
        String roleId = login.getRoleId();
        //如果是单位主要领导管理员，查看单位所有的 任务
        if ("02".equals(roleId)) {
            String deptId = login.getDeptId();
            filter.setDeptId(deptId);
            filter.setUserId(null);
            filter.setStatus("2");
            filter.setType("0");
            taskUnitList = taskUnitService.queryFilter(filter);
            filter.setType("5");
            taskUnitList.addAll(taskUnitService.queryFilter(filter));
            //查询当前
        } else {
            //只查看自己的任务
            filter.setUserId(userId);
            filter.setType("0");
            taskUnitList = taskUnitService.queryFilter(filter);
            filter.setType("5");
            taskUnitList.addAll(taskUnitService.queryFilter(filter));
        }
        if (ObjectUtils.isNotBlank(taskUnitList)) {
            return coverMessage("200", "success", taskUnitList);
        } else {
            return coverMessage("500", "无任务");
        }
    }

    /**
     * 单位任务详情
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/taskUnitDetail", method = RequestMethod.POST)
    public Message taskUnitDetail(@RequestBody TaskUnitFilter filter) {
        if (StringUtils.isBlank(filter.getSysId())) {
            return coverMessage("500");
        } else {
            Map<String, Object> map = new HashMap<>();
            String taskUnitId = filter.getSysId();
            String userId = filter.getUserId();
            SysLogin sysLogin = sysLoginService.getById(userId);
            String deptId = sysLogin.getDeptId();
            TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
            //如果当前任务是待签收，查看时将任务更新为以签收
            if ("0".equals(taskUnit.getType())) {
                taskUnit.setType("5");
                taskUnitService.update(taskUnit);
            }
            String taskMainId = taskUnit.getTaskMainId();
            //牵头单位名称集合
            String leadDepts = "";
            List<TaskUnit> leadDeptList = taskUnitService.getBySubIdAndUnitType(taskUnit.getTaskSubId(), "1", taskUnit.getTimeRound());
            for (TaskUnit unit : leadDeptList) {
                leadDepts += (unit.getDeptName() + " ");
            }
            //协办单位名称集合
            String xbDepts = "";
            List<TaskUnit> xbDeptList = taskUnitService.getBySubIdAndUnitType(taskUnit.getTaskSubId(), "2", taskUnit.getTimeRound());
            for (TaskUnit unit : xbDeptList) {
                xbDepts += (unit.getDeptName() + " ");
            }
            TaskMain taskMain = taskMainService.getById(taskMainId);
    /*     List<TaskUser> taskUserList = taskUserService.getByTaskUnitId(taskUnitId);
       List<Map> list = new ArrayList<>();
        for (TaskUser taskUser : taskUserList) {
            SysUser sysUser = sysUserService.getById(taskUser.getUnitUserId());
            Map<String, Object> map = new HashMap<>();
            map.put("sysUser", sysUser);
            map.put("taskUser", taskUser);
            list.add(map);
        }*/
            String userCreate = "";
            if ("03".equals(sysLogin.getRoleId()) || "04".equals(sysLogin.getRoleId())) {
                TaskUserFilter taskUserFilter = new TaskUserFilter();
                taskUserFilter.setTaskUnitId(taskUnitId);
                taskUserFilter.setUnitUserId(userId);
                List<TaskUser> taskUsers = taskUserService.queryFilter(taskUserFilter);
                if (ObjectUtils.isNotBlank(taskUsers)) {
                    for (TaskUser taskUser : taskUsers) {
                        //如果登录用户是分管或者经办人 ，判断当前人员任务状态
                        if ("0".equals(taskUser.getStatus())) {
                            //待签收时查看的 时候将状态改为已签收5
                            taskUser.setStatus("5");
                            taskUserService.update(taskUser);
                        }
                    }
                    userCreate = taskUsers.get(0).getCreateUser();
                }
            }
            //当前单位任务的所有反馈
            List<TaskBackNew> taskBackNews = taskBackNewService.getByTaskUnitId(taskUnitId);
            //任务创建人id
            String mainCreateUser = taskMain.getCreateUser();
            map.put("userCreate", userCreate);
            map.put("mainCreateUser", mainCreateUser);
            //当前登录人的反馈信息
            List<TaskBackNew> myBackList = taskBackNewService.getByTaskUnitIdAndSenderId(taskUnitId, userId);
            //反馈给我的信息
            List<TaskBackNew> giveMeBackList = taskBackNewService.getByTaskUnitIdAndRecipientId(taskUnitId, userId);
            //协办反馈给单位的
            List<TaskBackNew> giveDeptBackList = taskBackNewService.getByTaskUnitIdAndReceiveDeptAndSubId(taskUnitId, deptId, taskUnit.getTaskSubId());
            //当前人员批转给下级的任务
            List<TaskUser> taskUserList = taskUserService.getByCreateUserAndTaskUnitId(userId, taskUnitId);
//流程记录
            List<TaskLogNew> logNewList = taskLogNewService.getByUnitId(taskUnitId);

            //历史轮次
            List<Map<String, Object>> oldTask = taskUnitService.getByOldTaskUnit(taskUnit.getTaskSubId(), deptId);
            map.put("taskMain", taskMain);
            map.put("taskUnit", taskUnit);
            map.put("giveMeBackList", giveMeBackList);
            map.put("giveDeptBackList", giveDeptBackList);
            map.put("logNewList", logNewList);
            map.put("xbDepts", xbDepts);
            map.put("leadDepts", leadDepts);
            return coverMessage("200", "success", map);
        }
    }


    /**
     * 协办任务列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/xbDeptList", method = RequestMethod.POST)
    public Message xbDeptList(@RequestBody TaskUnitFilter filter) {
        try {
            TaskUnit taskUnit = taskUnitService.getById(filter.getSysId());
            List<TaskUnit> xbDeptList = taskUnitService.getBySubIdAndUnitType(taskUnit.getTaskSubId(), "2", taskUnit.getTimeRound());
            if (ObjectUtils.isNotBlank(xbDeptList)) {
                return coverMessage("200", "协办任务列表", xbDeptList);
            } else {
                return coverMessage("500", "error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 单位领导催办批转的经办人员
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/hastenUser", method = RequestMethod.POST)
    public Message hastenUser(@RequestBody HastenMessageFilter filter) {
        try {
            TaskUnit taskUnit = taskUnitService.getById(filter.getTaskUnitId());
            String createId = filter.getCreateId();
            String userId = filter.getUserId();
            SysUserDataBean sysUser = sysUserService.getUserDataBeanById(createId);
            SysUserDataBean user = sysUserService.getUserDataBeanById(userId);
            HastenMessage hastenMessage = new HastenMessage();
            BeanUtils.copyProperties(filter, hastenMessage);
            hastenMessage.setCreateUserName(sysUser.getName());
            hastenMessage.setStatus("0");//设置催办状态为未读
            hastenMessage.setDeptId(taskUnit.getDeptId());
            hastenMessage.setTaskSubId(taskUnit.getTaskSubId());
            hastenMessage.setUserId(userId);//保存接收催办信息的userid
            hastenMessage.setUserName(user.getName());
            hastenMessage.setTaskMainName(taskUnit.getTaskMainName());
            hastenMessage.setTaskSubName(taskUnit.getTaskSubName());
            String mobile = user.getMobile();
            //催办短信
            smsUtilService.taskHastenMessage(taskUnit, hastenMessage, sysUserService.getById(userId));
            hastenMessageService.save(hastenMessage, createId);
            return coverMessage("200", "催办成功");
        } catch (BeansException e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 我的反馈记录
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/myBackList", method = RequestMethod.POST)
    public Message myBackList(@RequestBody TaskUnitFilter filter) {
        if (StringUtils.isBlank(filter.getSysId())) {
            return coverMessage("500");
        } else {
            Map<String, Object> map = new HashMap<>();
            String taskUnitId = filter.getSysId();
            String userId = filter.getUserId();
            SysLogin sysLogin = sysLoginService.getById(userId);
            String deptId = sysLogin.getDeptId();
            TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
            //如果当前任务是待签收，查看时将任务更新为以签收
            //当前登录人的反馈信息
            List<TaskBackNew> myBackList = taskBackNewService.getByTaskUnitIdAndSenderId(taskUnitId, userId);
            //流程记录
            List<TaskLogNew> logNewList = taskLogNewService.getByUnitId(taskUnitId);
            map.put("myBackList", myBackList);
            map.put("logNewList", logNewList);
            return coverMessage("200", "success", map);
        }
    }

    /**
     * 批转页面可批转用户列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/endorseList", method = RequestMethod.POST)
    public Message endorseList(@RequestBody TaskUnitFilter filter) {
        String userId = filter.getUserId();
        String taskUnitId = filter.getSysId();
        List<SysUser> userList = taskUnitService.queryEndorseList(taskUnitId, userId);
        if (ObjectUtils.isBlank(userList)) {
            return coverMessage("500");
        } else {
            return coverMessage("200", "success", userList);
        }
    }

    /**
     * y已批转人员
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/taskUserList", method = RequestMethod.POST)
    public Message taskUserList(@RequestBody TaskUnitFilter filter) {
        //当前人员批转给下级的任务
        try {
            List<TaskUser> taskUserList = taskUserService.getByCreateUserAndTaskUnitId(filter.getUserId(), filter.getSysId());
            return coverMessage("200", "已批转人员", taskUserList);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 更新当前批转下去的任务（将当前人员任务失效，生效）
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateTaskUser")
    public Message updateTaskUser(@RequestBody TaskUserFilter filter) {
        String result = taskUserService.updateTaskUser(filter.getSysId());
        if ("200".equals(result)) {
            return coverMessage("200", "删除成功");
        } else {
            return coverMessage("500", "error");
        }
    }

    /**
     * 保存批转人员任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveTaskUser", method = RequestMethod.POST)
    public Message saveTaskUser(@RequestBody TaskUnitFilter filter) {
        //userId  当前用户 sysId 单位任务id  taskUsers  批转人员id字符串，逗号拼接
        String s = taskUnitService.saveTaskUser(filter);
        if ("200".equals(s)) {
            return coverMessage("200", "保存成功");
        } else {
            return coverMessage("500", "未添加经办人");
        }
    }

    /**
     * 退回重办
     *
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public Message updateStatus(@RequestBody TaskBackNewFilter filter) {
        String s = taskBackNewService.updateUnitStatus(filter);
        if ("200".equals(s)) {
            return coverMessage("200", "办理成功");
        } else {
            return coverMessage("500", "办理失败");
        }
    }

    /**
     * 保存反馈信息
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveTaskBack", method = RequestMethod.POST)
    public Message saveTaskBack(@RequestBody TaskBackNewFilter filter) {
        //createId  当前用户id
        String s = taskBackNewService.saveBack(filter);
        if ("200".equals(s)) {
            return coverMessage("200", "反馈成功");
        } else if ("500".equals(s)) {
            return coverMessage("500", "反馈失败");
        } else {
            return coverMessage("500", s);
        }
    }

    /**
     * 单位任务统计汇总
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/orderStatistics", method = RequestMethod.POST)
    public Message orderStatistics(@RequestBody SysUserDataBean dataBean) {
        String userId = dataBean.getUserId();
        String time = dataBean.getTime();
        String substring = time.substring(0, time.indexOf("-"));
        SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(userId);
        Map<String, Object> resultMap = new HashMap();
        if ("02".equals(userDataBean.getRoleId())) {
            //单位账号查看全部单位任务
            TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
            taskUnitFilter.setDeptId(userDataBean.getDeptId());
            for (int i = 0; i < 2; i++) {
                if (i == 0) {
                    taskUnitFilter.setCreateDate(time);
                    Map<String, Object> objectMap = orderUnitMap(taskUnitFilter);
                    resultMap.put("month", objectMap);
                } else {
                    taskUnitFilter = new TaskUnitFilter();
                    taskUnitFilter.setDeptId(userDataBean.getDeptId());
                    taskUnitFilter.setCreateDate(substring);
                    Map<String, Object> objectMap = orderUnitMap(taskUnitFilter);
                    resultMap.put("year", objectMap);
                }
            }
        } else {
            //个人账号查看个人任务
            //单位账号查看全部单位任务
            TaskUserFilter taskUserFilter = new TaskUserFilter();
            taskUserFilter.setUnitUserId(userDataBean.getUserId());
            for (int i = 0; i < 2; i++) {
                if (i == 0) {
                    taskUserFilter.setCreateDate(time);
                    Map<String, Object> objectMap = orderUserMap(taskUserFilter);
                    resultMap.put("month", objectMap);
                } else {
                    taskUserFilter.setCreateDate(substring);
                    Map<String, Object> objectMap = orderUserMap(taskUserFilter);
                    resultMap.put("year", objectMap);
                }
            }
        }
        return coverMessage("200", "统计列表", resultMap);
    }

    public Map<String, Object> orderUnitMap(TaskUnitFilter taskUnitFilter) {

        //当前查询月份所有任务
        List<TaskUnit> allTaskUnits = taskUnitService.queryStatistics(taskUnitFilter);
        //当前查询月份已完成任务
        taskUnitFilter.setType("4");
        List<TaskUnit> doneTaskUnits = taskUnitService.queryStatistics(taskUnitFilter);
        //逾期
        taskUnitFilter.setType(null);
        taskUnitFilter.setOverdueDay("1");
        List<TaskUnit> overdueTaskUnits = taskUnitService.queryStatistics(taskUnitFilter);
        //退回
        taskUnitFilter.setOverdueDay(null);
        taskUnitFilter.setBackNum("1");
        List<TaskUnit> backTaskUnits = taskUnitService.queryStatistics(taskUnitFilter);
        String allInt = allTaskUnits.size() + "";
        String doneInt = doneTaskUnits.size() + "";
        String overdueInt = overdueTaskUnits.size() + "";
        String backInt = backTaskUnits.size() + "";
        Map<String, Object> map = new HashMap<>();
        map.put("allInt", allInt);
        map.put("doneInt", doneInt);
        map.put("overdueInt", overdueInt);
        map.put("backInt", backInt);
        return map;
    }

    public Map<String, Object> orderUserMap(TaskUserFilter taskUserFilter) {

        //当前查询月份所有任务
        List<TaskUser> allTaskUsers = taskUserService.queryStatistics(taskUserFilter);
        //当前查询月份已完成任务
        taskUserFilter.setStatus("4");
        List<TaskUser> doneTaskUsers = taskUserService.queryStatistics(taskUserFilter);
        //逾期
        taskUserFilter.setStatus(null);
        taskUserFilter.setOverdueDay("1");
        List<TaskUser> overdueTaskUsers = taskUserService.queryStatistics(taskUserFilter);
        //退回
        taskUserFilter.setOverdueDay(null);
        taskUserFilter.setBackNum("1");
        List<TaskUser> backTaskUsers = taskUserService.queryStatistics(taskUserFilter);
        String allInt = allTaskUsers.size() + "";
        String doneInt = doneTaskUsers.size() + "";
        String overdueInt = overdueTaskUsers.size() + "";
        String backInt = backTaskUsers.size() + "";
        Map<String, Object> map = new HashMap<>();
        map.put("allInt", allInt);
        map.put("doneInt", doneInt);
        map.put("overdueInt", overdueInt);
        map.put("backInt", backInt);
        return map;
    }

    /**
     * 删除撤回反馈信息
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delTaskBack", method = RequestMethod.POST)
    public Message delTaskBack(@RequestBody TaskBackNewFilter filter) {
        try {
            TaskBackNew taskBackNew = taskBackNewService.getById(filter.getSysId());
            if ("3".equals(taskBackNew.getStatus())) {
                //已反馈但是上级未做评价
                taskBackNew.setDel("0");
                taskBackNewService.update(taskBackNew);
                return coverMessage("200", "删除成功");
            } else {
                return coverMessage("500", "反馈信息已查看,无法删除");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }
}
